﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace Sunyi.Project.WebPoint.Common
{
    public static class EncrpytionHelper
    {
        public static string EncrpytByMD5(string inputString)
        {
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();

            byte[] hash= provider.ComputeHash(EnvironmentSetting.DefaultEncoding.GetBytes(inputString));

            return Convert.ToBase64String(hash);
        }

        public static string TripleDesEncrypt(byte[] source, byte[] Key, byte[] IV)
        {
            byte[] encryptedData = null;

            var desCryptoServiceProvider = new TripleDESCryptoServiceProvider();
            var transform = desCryptoServiceProvider.CreateEncryptor(Key, IV);

            using (MemoryStream ms = new MemoryStream())
            {
                CryptoStream stream = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                stream.Write(source, 0, source.Length);
                stream.FlushFinalBlock();

                encryptedData = ms.ToArray();
            }

            return Convert.ToBase64String(encryptedData);
        }

        public static string TripleDesDecrypt(byte[] source, byte[] Key, byte[] IV)
        {
            byte[] decryptedData = null;
            byte[] buffer = new byte[source.Length];

            var desCryptoServiceProvider = new TripleDESCryptoServiceProvider();
            var transform = desCryptoServiceProvider.CreateDecryptor(Key, IV);

            using (MemoryStream ms = new MemoryStream(source))
            {
                CryptoStream stream = new CryptoStream(ms, transform, CryptoStreamMode.Read);

                int length = stream.Read(buffer, 0, buffer.Length);
                decryptedData = new byte[length];
                Array.Copy(buffer, decryptedData, length);
            }

            return EnvironmentSetting.DefaultEncoding.GetString(decryptedData);
        }
    }
}
